#include <iostream>
#include <string>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstdlib>
#include <unistd.h>
#include "log.hpp"

log ls;

using std::stoi;
using std::string;
using std::getline;
using std::cin;
using std::cout;
using std::cerr;
using std::endl;


struct ThreadData{
    sockaddr_in server;
    int sockfd;
    string serverip;
};

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

void *receive(void *arg)
{
    ThreadData* td = static_cast<ThreadData*>(arg);
    while (true)
    {
        sockaddr_in rec;
        bzero(&rec, sizeof(rec));
        char buf[2024] = {0};
        socklen_t len = sizeof(rec);
        ssize_t n = recvfrom(td->sockfd, buf, sizeof(buf), 0, (sockaddr *)&rec, &len);

        if(n > 0){
            buf[n] = 0;
            cerr << buf << endl;
        }
        else
            break;
    }
    return nullptr;
}

void *send(void *arg)
{   
    ThreadData* td = static_cast<ThreadData*>(arg);
    
    socklen_t len = sizeof(td->server);

    std::string welcome = td->serverip;
    welcome += " comming...";

    // printf("ip: %s, port: %d\n", inet_ntoa(td->server.sin_addr), ntohs(td->server.sin_port));
    
    ssize_t nn = sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (struct sockaddr *)&(td->server), len);
    // if(nn < 0){
    //     ls(Warning, "sendto error errno: %d,err string: %s", errno, strerror(errno));
    // }
    // else{
    //     ls(Info, "sendto success:  _sockfd: %d", td->sockfd);
    // }
    while (true)
    {
        cout << "say out: ";
        string say;
        getline(cin, say);
        // cout << say << endl;
        ssize_t n = sendto(td->sockfd, say.c_str(), say.size(), 0, (sockaddr *)&(td->server), len);
        if(n < 0){
            ls(Warning, "sendto error errno: %d,err string: %s", errno, strerror(errno));
            continue;
        }
        // else{
        //     ls(Info, "sendto success:  _sockfd: %d", td->sockfd);
        // }
    }
    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    ThreadData td;
    bzero(&td, sizeof(td));
    td.serverip = ip;
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0){
        ls(Fatal, "socker error, _sockfd: %d", td.sockfd);
        exit(1);
    }

    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(port);
    td.server.sin_addr.s_addr = inet_addr(ip.c_str());

    pthread_t r, s;
    pthread_create(&r, nullptr, receive, &td);
    pthread_create(&s, nullptr, send, &td);

    pthread_join(r, nullptr);
    pthread_join(s, nullptr);
    close(td.sockfd);
    return 0;
}